package org.tgcloud.group.service.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.tgcloud.group.core.BeanUtil;
import org.tgcloud.group.core.RedisUtil;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.entity.MjBusinessPerson;
import org.tgcloud.group.entity.MjBusinessTimePrice;
import org.tgcloud.group.repository.MjBusinessPersonMapper;
import org.tgcloud.group.repository.MjBusinessTimePriceMapper;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhy
 * @create: 2023-11-30 15:14
 * @description: 商务相关的定时任务
 */
@Slf4j
@Component
public class BusinessTask {

    @Autowired
    private MjBusinessTimePriceMapper businessTimePriceMapper;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    @Scheduled(cron = "0 0 1 1 * ?")
    public void doAddBusinessTime(){
        if (RedisUtil.existKey("doAddBusinessTime")){
            return;
        }
        RedisUtil.setCacheObject("doAddBusinessTime", "doAddBusinessTime", 60L, TimeUnit.SECONDS);
        try {
            // 查询出在职的员工
            List<MjBusinessPerson> businessPeople = businessPersonMapper.selectTaskListByStatus();
            if (!BeanUtil.isNullList(businessPeople)){
                for (MjBusinessPerson businessPerson : businessPeople) {
                    // 查询出当月是否添加了记录
                    MjBusinessTimePrice businessTimePrice = businessTimePriceMapper.selectTaskMsgByBusinessIdAndTime(businessPerson.getId(), new Date());
                    if (null == businessTimePrice){
                        MjBusinessTimePrice timePrice = new MjBusinessTimePrice();
                        timePrice.setBusinessId(businessPerson.getId());
                        timePrice.setChooseTime(new Date());
                        timePrice.setBasicSalary(businessPerson.getBasicSalary() != null ? businessPerson.getBasicSalary() : BigDecimal.ZERO);
                        timePrice.setPerformanceGoodsPrice(businessPerson.getPerformanceGoodsValue() != null ? new BigDecimal(businessPerson.getPerformanceGoodsValue()) : BigDecimal.ZERO);
                        timePrice.setCreateTime(new Date());
                        timePrice.setUpdateTime(new Date());
                        timePrice.setStatus((short) 1);
                        businessTimePriceMapper.insertSelective(timePrice);
                    }
                }
            }
        }catch (Exception e){
            log.error("商务薪资添加定时任务出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

}
